package tlab;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

/**
 * TLAB测试伪共享问题
 *
 * @author xujian
 * Creation date 2024/8/15 0:18
 * @version 1.0
 */

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class TlabTest {

    public static void main(String[] args) throws RunnerException {
        Options build = new OptionsBuilder().include(TlabTest.class.getSimpleName())
                .forks(1)
                .warmupBatchSize(5)
                .measurementBatchSize(5)
                .threads(4).build();

        new Runner(build).run();
    }



    public static class MyObject{
        private volatile int val;

        public int getVal() {
            return val;
        }
    }


    @State(Scope.Thread)
    public static class MyCount{
        private MyObject[] myCounts = new MyObject[2];

        public MyCount() {
            myCounts[0] = new MyObject();
            myCounts[1] = new MyObject();
        }
    }


    @Benchmark
    @Group("SHARED")
    public void testA(MyCount myCount){
        myCount.myCounts[0].val++;
    }

    @Benchmark
    @Group("SHARED")
    public void testB(MyCount myCount){
        myCount.myCounts[1].val++;
    }


}
